package cn.lcfms.app.admin.controller;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import cn.lcfms.app.admin.bean.CategoryBean;
import cn.lcfms.app.admin.bean.CollectBean;
import cn.lcfms.bin.annotation.PermitPoll;
import cn.lcfms.bin.core.Application;
import cn.lcfms.bin.service.BaseService;
import cn.lcfms.bin.view.CommonEditView;
import cn.lcfms.bin.view.CommonPageLayer;
import cn.lcfms.cms.Collect;
import cn.lcfms.cms.Plagiarism;
import cn.lcfms.utils.StringUtils;


@PermitPoll(type="CMS管理",name="CMS工具")
@Controller("admin.CmsToolController")
@RequestMapping("/admin/cmstool")
public class CmsToolController extends AdminBaseController{
	
	private Collect coll=Collect.getColl();
	
	@RequestMapping("/plagiarism")
	public CommonEditView plagiarism() {
		CommonEditView view=new CommonEditView("仿站工具");
		view.setInputForm("网页链接", "url", "", "unempty");
		view.setInputForm("网页编码", "charset", "utf-8", "unempty");
		view.setTextareaForm("cookie", "cookie", "", 1000);
		view.setInputForm("模板文件", "template", "newFile.jsp", "unempty");
		view.setInputForm("静态目录", "statics", "index", "unempty");
		view.setInputForm("额外图片", "img", "img[data-lazyload-img],div[data-original],b[data-original]", "");
		view.setFormAction("savePlag");
		return view;
	}
	
	@RequestMapping("/savePlag")
	public String savePlag(String url,String img,String charset,String cookie,String template,String statics) throws IOException {
		if(!url.startsWith("http")) {
			return "{code:0,msg:url必须以http打头}";
		}
		Plagiarism plag=new Plagiarism(url,charset,cookie,template, statics,"jsp");
		if(img!=null && !img.equals("")) {
			plag.setImgcode(img);
		}
		String error;
		while ((error=plag.getError())==null) {	
			if(plag.getAct()==10) {
				if(statics.indexOf(":")==-1 && template.indexOf(":")==-1) {					
			    	String temp=template.replace(".jsp", "");
			    	return "{code:1,msg:创建成功，正在跳转到预览,window:true,url:show?t="+temp+"&s="+statics+"}";
				}else {
					return "{code:1,url:plagiarism,msg:创建成功，绝对路径下不支持预览}";
				}				
			}
		}
		return "{code:0,msg:"+error+"}";
	}
	
	@RequestMapping("/show")
	public String show(String t,String s,HttpServletRequest request) {
		String basePath=(String) request.getAttribute("APP");
		request.setAttribute("JS", basePath+"statics/"+s+"/js/"); 
    	request.setAttribute("CSS", basePath+"statics/"+s+"/css/"); 
    	request.setAttribute("IMG", basePath+"statics/"+s+"/images/"); 
    	return t;
	}
	
	@RequestMapping("/collect")
	public CommonEditView collect(@RequestParam(value="id",required=false,defaultValue="0") int id) {
		CommonEditView view=new CommonEditView("采集工具");
		BaseService cate=Application.getService(CategoryBean.class);
		cate.column("id","title");
		List<HashMap<String, Object>> catelist = cate.selectList();
		BaseService mark=Application.getService("mark");
		List<HashMap<String, Object>> marklist = mark.column("title").selectList();
		view.addObject("cate", catelist);
		view.addObject("mark", marklist);
		view.addObject("tempId", id);
		if(id==0) {
			view.setRadioForm("采集模式", "type", "搜索引擎模式,排序模式,指定页面模式", "1,2,3", 2);
			view.setInputForm("起始地址", "url", "", "");
			view.setInputForm("url表达式", "preg", "", "");
			view.setInputForm("开始数字", "begin", "0", "+integer");
			view.setInputForm("结束数字", "end", "10000", "+integer");
			view.setInputForm("编码", "charset", "utf-8", "unempty");
			File file=new File(Application.ROOT_PATH+"WEB-INF"+Application.F+"classes"+Application.F+"cn"+Application.F+"lcfms"+Application.F+"cms"+Application.F+"collect");
			String[] list = file.list();
			view.setSelectForm("实现类", "impl", StringUtils.join(list, ","), StringUtils.join(list, ","),"InsertArticle.class");	
			view.setTextareaForm("cookie", "cookie", "", 1000);
			view.addObject("property", "[{pkey:'title',pvalue:'/title/'},{pkey:'details',pvalue:'/p/'}]");
			view.addObject("type", 2);
		}else {
			CollectBean bean=Application.getService(CollectBean.class).selectOne(CollectBean.class, id);
			view.setRadioForm("采集模式", "type", "搜索引擎模式,排序模式,指定页面模式", "1,2,3", bean.getType());
			view.setInputForm("起始地址", "url", bean.getUrl(), "");
			view.setInputForm("url表达式", "preg", bean.getPreg(), "");
			view.setInputForm("开始数字", "begin", bean.getBegin(), "+integer");
			view.setInputForm("结束数字", "end", bean.getEnd(), "+integer");
			view.setInputForm("编码", "charset", bean.getCharset(), "unempty");
			File file=new File(Application.ROOT_PATH+"WEB-INF"+Application.F+"classes"+Application.F+"cn"+Application.F+"lcfms"+Application.F+"cms"+Application.F+"collect");
			String[] list = file.list();
			view.setSelectForm("实现类", "impl", StringUtils.join(list, ","), StringUtils.join(list, ","),bean.getImpl());	
			view.setTextareaForm("cookie", "cookie", bean.getCookie(), 1000);
			view.addObject("property",bean.getProperty()==null || "".equals(bean.getProperty())?"[]":bean.getProperty());
			view.addObject("type", bean.getType());
		}		
		view.setViewForm("frame/collect.jsp");
		view.clearSubmitButton();
		view.setSubmitButton("添加属性","addpropery","icon-jia"); 
		view.setSubmitButton("开始采集","start","fa-refresh");
		view.setSubmitButton("暂停采集","pause","fa-pause");
		view.setSubmitButton("停止采集","stop","fa-stop");
		view.setSubmitButton("保存模板","saveTemp","fa-save");
		view.setSubmitButton("使用模板","changeTemp","fa-check-square");
		view.displayNoneShade();
		view.setFormAction("saveCollect");
		return view;
	}
	
	
	@RequestMapping("/saveCollect")
	public String saveCollect(CollectBean bean) throws IOException {
		if(Collect.getColl().getStatus()==0) {
			coll.setBean(bean);
			int type=bean.getType();
			if(type==1 || type==3) {
				if(bean.getUrl().equals("") || !bean.getUrl().startsWith("http")) {
					return "{code:0,msg:起始地址不能为空且必须以http打头}";
				}
			}
			if(type==2) {
				String preg = bean.getPreg();
				if(!preg.startsWith("http") || preg.indexOf("{数字}")==-1) {
					return "{code:0,msg:url表达式不正确}";
				}
			}
			if(bean.getProperty()==null) {
				return "{code:0,msg:属性不能为空}";
			}			
			coll.start();			
			return "{code:1,msg:采集已启动}";
		}
		if(coll.getStatus()==1) {
			return "{code:0,msg:采集正在运行，不能重复操作}";
		}
		if(coll.getStatus()==2) {
			coll.start();
			return "{code:1,msg:采集已启动}";
		}
		return "{code:0}";
	}
	
	
	
	@RequestMapping("/stopCollect")
	public String stopCollect() {
		if(Collect.getColl().getStatus()==0) {
			return "{code:1,msg:你特么逗我，老子还没开始}";
		}
		coll.stop();
		return "{code:1,msg:采集已完成，共采集数据"+coll.getNum()+"条}";
	}
	
	@RequestMapping("/pauseCollect")
	public String pauseCollect() {
		if(Collect.getColl().getStatus()!=1) {
			return "{code:1,msg:你特么逗我，老子又没开始}";
		}
		coll.pause();
		return "{code:1,msg:采集已暂停}";
	}
	
	@RequestMapping("/saveTemp")
	public String saveTemp(CollectBean bean) {
		BaseService service = Application.getService(CollectBean.class);
		service.insert(bean);
		return "{code:1,msg:保存成功,id:"+service.insert_id()+"}";
	}
	
	@RequestMapping("/updateTemp")
	public String updateTemp(CollectBean bean) {
		BaseService service = Application.getService(CollectBean.class);
		service.update(bean,"title");
		return "{code:1,msg:保存成功}";
	}
	
	@RequestMapping("/deleteTemp")
	public String deleteTemp(int id) {
		BaseService service = Application.getService(CollectBean.class);
		service.deleteById(id);
		return "local:TempList";
	}
	
	@RequestMapping("/TempList")
	public CommonPageLayer TempList(HttpServletRequest request) {
		BaseService service=Application.getService(CollectBean.class);
		service.column("title as 标题");
		service.column("type as 采集模式",(Object object)->{
			int type=(int)object;
			if(type==1) {
				return "搜索引擎模式";
			}
			if(type==2) {
				return "排序模式";
			}
			if(type==3) {
				return "指定页面模式";
			}
			return "";
		});
		service.column("id as 查看",(Object object)->{
			String basePath=(String) request.getAttribute("APP");
			String delePath=basePath+"admin/cmstool/deleteTemp?id="+object;		
			return "<a class=\"btn btn-xs btn-primary\" href=\"javascript:parent.checkTemp("+object+");\"><i class=\"iconfont icon-xuanze align-top bigger-125\"></i> 选择</a>&nbsp;&nbsp;"
				 + "<a class=\"btn btn-xs btn-primary\" href=\""+delePath+"\"><i class=\"iconfont icon-lajitong align-top bigger-125\"></i> 删除</a>";
		});
		CommonPageLayer layer=new CommonPageLayer(service);		
		return layer;
	}
	
	
	public static void main(String[] args) {
		
	}
}
